<?php
/**
 * Ly - Mysql数据库驱动类
 *
 * 提供Mysql数据库的驱动功能
 *
 * Copyright (c) 2013 YinHailin All rights reserved.
 * @Author: YinHailin
 * @Authorize: Boren Network
 * @Created by YinHailin at 2013-11-01
 */

defined('LY_VERSION') or exit();

class MysqlDb extends DbCore {

  /*
   * 构造方法
   * @param array $config 数据库连接配置参数
   */
  public function __construct($config = '') {
    if (!extension_loaded('mysql')) {
      halt('服务器不支持mysql扩展', __FILE__, __LINE__);
    }
    if (!empty($config)) {
      $this->Config = $config;
    }
  }

  /*
   * 释放数据库查询结果
   * @param resource $linkId 数据库连接ID
   * @param array $config 数据库连接配置
   * @return object
   */
  public function Connect($linkId = 0, $config = '') {
    if (!isset($this->LinkIdList[$linkId])) {
      if (empty($config)) $config = $this->Config;
      //host处理
      $host = $config['host'].($config['port'] ? ':'.$config['port'] : '');
      //连接数据库
      $this->LinkIdList[$linkId] = mysql_connect($host, $config['user'], $config['password'], true, 131072);
      if (!$this->LinkIdList[$linkId] || (!empty($config['database']) && !mysql_select_db($config['database'], $this->LinkIdList[$linkId])) ) {
        halt(mysql_error(), __FILE__, __LINE__);
      }
      //设置数据库字符编码
      mysql_query("SET NAMES '".C('DB_CHARSET')."'", $this->LinkIdList[$linkId]);
      $dbVersion = mysql_get_server_info($this->LinkIdList[$linkId]);
      //设置 sql_model
      if ($dbVersion >'5.0.1') {
        mysql_query("SET sql_mode=''", $this->LinkIdList[$linkId]);
      }
      //设置连接成功标识
      $this->Connected = true;
    }
    return $this->LinkIdList[$linkId];
  }

  /*
   * 数据库错误信息
   + 显示当前的SQL语句
   * @access public
   * @return string
   */
  public function Error() {
    $this->Error = mysql_error($this->CurLinkId);
    if ('' != $this->QueryStr) {
      $this->Error .= "\n [ SQL语句 ] : ".$this->QueryStr;
    }
    return $this->Error;
  }

  /*
   * 获取所有查询到的数据
   * @return array
   */
  public function GetAll() {
    $result = array();
    if ($this->NumRows > 0) {
      while ($rows = mysql_fetch_assoc($this->CurQueryId)) {
        $result[] = $rows;
      }
      mysql_data_seek($this->CurQueryId, 0);
    }
    return $result;
  }

  /*
   * SQL查询
   * @param array $data 数据
   * @return false | array
   */
  public function Query($sql) {
    $this->InitConnect();
    if (!$this->CurLinkId) { return false;}
    $this->QueryStr = $sql;
    //释放上次查询资源
    if ($this->CurQueryId) { $this->Free();}
    $this->CurQueryId = mysql_query($sql, $this->CurLinkId);
    if ($this->CurQueryId === false) {
      //出错处理
      halt($this->Error(), __FILE__, __LINE__);
      return false;
    } else {
      $this->NumRows = mysql_num_rows($this->CurQueryId);
      return $this->getAll();
    }
  }

  /*
   * 执行SQL
   * @param array $data 数据
   * @return false | integer
   */
  public function Execute($sql) {
    $this->InitConnect();
    if (!$this->CurLinkId) { return false;}
    $this->QueryStr = $sql;
    //释放上次查询资源
    if ($this->CurQueryId) { $this->Free();}
    $result = mysql_query($sql, $this->CurLinkId);
    if ($result === false) {
      //出错处理
      halt($this->Error(), __FILE__, __LINE__);
      return false;
    } else {
      $this->NumRows = mysql_affected_rows($this->CurLinkId);
      $this->LastInsertId = mysql_insert_id($this->CurLinkId);
      return $this->NumRows;
    }
  }

  /*
   * 字段名解析
   + 字段名或表名两端添加 ` 符号
   * @param string $key 字段名
   * @return string
   */
  public function ParseKey($key) {
    $key = trim($key);
    if (!preg_match('/[,\'\"\*\(\)`.\s]/', $key)) {
      $key = '`'.$key.'`';
    }
    return $key;
  }

  /*
   * SQL指令字符串安全过滤
   * @param string $string SQL指令字符串
   * @return string
   */
  public function FilterString($string) {
    if($this->CurLinkId) {
      return mysql_real_escape_string($string,$this->CurLinkId);
    }else{
      return mysql_escape_string($string);
    }
    return $string;
  }

  /*
   * 释放数据库查询结果
   * @param array $data 数据
   * @param array $options 参数
   * @return false | integer
   */
  public function Free() {
    mysql_free_result($this->CurQueryId);
    $this->CurQueryId = null;
  }

  /*
   * 取得数据表的字段信息
   * @param string $tableName 数据表名称
   * @return array
   */
  public function GetFields($tableName) {
    $result = $this->Query('SHOW COLUMNS FROM '.$this->ParseKey($tableName));
    $info = array();
    if ($result) {
      foreach ($result as $key => $value) {
        $info[$value['Field']] = array(
          'name' => $value['Field'],
          'type' => $value['Type'],
          'notnull' => $value['Null'] === '',
          'default' => $value['Default'],
          'primary' => strtolower($value['Key']) == 'pri',
          'autoinc' => strtolower($value['Extra']) == 'auto_increment',
        );
      }
    }
    return $info;
  }

  /**
   * 取得数据库的表信息
   * @param string $dbName 数据库名称
   * @return array
   */
  public function GetTables($dbName = '') {
    if (!empty($dbName)) {
      $sql = 'SHOW TABLES FROM '.$dbName;
    } else {
      $sql = 'SHOW TABLES ';
    }
    $result = $this->Query($sql);
    $info = array();
    foreach ($result as $key => $value) {
      $info[$key] = array_shift($value);
    }
    return $info;
  }

  /*
   * 关闭数据库
   */
  public function Close() {
    if ($this->CurLinkId) {
      mysql_close($this->CurLinkId);
    }
    $this->CurLinkId = null;
  }
}